package edu.tjut.tjutcommunity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.tjut.tjutcommunity.entity.*;
import edu.tjut.tjutcommunity.mapper.CommentMapper;
import edu.tjut.tjutcommunity.mapper.FloorMapper;
import edu.tjut.tjutcommunity.service.FloorService;
import edu.tjut.tjutcommunity.service.PostService;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.MessageQueueUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yhh
 * @since 2022-04-17
 */
@Service
public class FloorServiceImpl extends ServiceImpl<FloorMapper, Floor> implements FloorService {
    private static final ConcurrentHashMap<Integer, Object> lock = new ConcurrentHashMap<>();

    final
    FloorMapper floorMapper;
    final
    PostService postService;
    final
    UserService userService;

    final
    CommentMapper commentMapper;
    final
    MessageQueueUtils messageQueueUtils;

    public FloorServiceImpl(FloorMapper floorMapper, PostService postService, MessageQueueUtils messageQueueUtils, UserService userService, CommentMapper commentMapper) {
        this.floorMapper = floorMapper;
        this.postService = postService;
        this.messageQueueUtils = messageQueueUtils;
        this.userService = userService;
        this.commentMapper = commentMapper;
    }

    //    /**
//     * 添加楼层
//     *
//     * @param floor   楼层主体
//     * @param user    发起用户
//     * @param ordinal 图片序号
//     * @return
//     * @throws ClassNotFoundException
//     * @throws InvocationTargetException
//     * @throws PicNotFoundException
//     * @throws IllegalAccessException
//     * @throws NoSuchMethodException
//     */
//    @Override
//    public boolean addFloor(Floor floor, User user, Integer ordinal) throws ClassNotFoundException, InvocationTargetException, PicNotFoundException, IllegalAccessException, NoSuchMethodException {
//        floor.setUid(user.getUid());
//        floor.setUsername(user.getUsername());
//        QueryWrapper<Floor> qw = new QueryWrapper<>();
//        Integer pid = floor.getPid();
//        qw.eq("pid", pid);
//        //楼层更新
//        if (lock.get(pid) == null) {
//            lock.put(pid, floor);
//            Long count = floorMapper.selectCount(qw);
//            floor.setFloors(Math.toIntExact(count + 1));
//            lock.remove(pid);
//        }
//        //添加图片
//        if (ordinal != null && ordinal > 0) {
//            SetPic(floor, user.getStudentId(), "_floor_pic_", ordinal);
//        }
//        if (floorMapper.insert(floor) == 1) {
//            //更新post帖子的更新时间
//            if (!postService.updateTime(pid)) return false;
//            //后续应该在这里添加通知帖子的用户有人回复了他的帖子
//            //根据帖子id获得帖子的uid和username
//            Post post = postService.getUidAndUsernameByPid(pid);
//            //比较帖子id和发起楼层id，如果不一样，证明是别人回复了帖子，予以通知
//            if (!Objects.equals(post.getUid(), user.getUid())) {
//                //获得被通知的楼主
//                User u = userService.getStuIdById(post.getUid());
//                NoticeMessage noticeMessage = NoticeMessage.getReplyMessage(user, pid, floor.getContent());
//                //发送
//                messageQueueUtils.sendMessage(u.getStudentId(), noticeMessage);
//            }
//            return true;
//        }
//
//        return false;
//    }
    @Override
    public Floor addFloor(Floor floor, User user) {
        floor.setUid(user.getUid());
        floor.setUsername(user.getUsername());
        floor.setAcademyName(user.getAcademyName());
        Integer pid = floor.getPid();
        Post post = postService.getUidAndUsernameAndFloorsByPid(pid);
        //楼层更新
        while (lock.get(pid) != null) ;
        try {
            lock.put(pid, floor);
            floor.setFloors(post.getFloors() + 2);
            if (floorMapper.insert(floor) == 1) {
                //更新post帖子的更新时间
                if (!postService.updateTime(pid)) return null;
                //更新帖子的楼层数
                if (!postService.floorsInc(pid)) return null;

                //比较帖子id和发起楼层id，如果不一样，证明是别人回复了帖子，予以通知
                if (!Objects.equals(post.getUid(), user.getUid())) {
                    //通过帖子的uid获得被通知的楼主stuid
                    User u = userService.getStuIdById(post.getUid());
                    NoticeMessage noticeMessage = NoticeMessage.getReplyPostMessage(user, pid, floor.getContent());
                    //发送
                    messageQueueUtils.sendMessage(u.getStudentId(), noticeMessage);
                }
                return floor;
            }
        } catch (Exception e) {
            System.out.println("插入帖子异常。。。");
            e.printStackTrace();
        } finally {
            lock.remove(pid);
        }
        return null;
    }

    @Override
    public Integer getPidByFid(Integer fid) {
        QueryWrapper<Floor> qw = new QueryWrapper<>();
        qw.select("pid");
        qw.eq("fid", fid);
        return floorMapper.selectOne(qw).getPid();

    }

    @Override
    public PageResult<Floor> getFloor(Integer pid, Integer pageNo) {
        Page<Floor> page = new Page<>(pageNo, 10);
        QueryWrapper<Floor> qw = new QueryWrapper<>();
        qw.eq("pid", pid);
        qw.orderByAsc("create_time");
        Page<Floor> floorPage = floorMapper.selectPage(page, qw);
        return new PageResult<>(floorPage.getRecords(), floorPage.getPages());
    }


    /**
     * 对应的楼层的回复数加一
     *
     * @param fid
     * @return
     */
    @Override
    public Boolean commentsInc(Integer fid) {
        Floor floor = floorMapper.selectById(fid);
        try {
            while (lock.get(fid) != null) ;
            lock.put(fid, floor);
            //comment里fid为此楼的总数+1
            floor.setComments(floor.getComments() + 1);
            floorMapper.updateById(floor);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            lock.remove(fid);
        }
    }

    /**
     * 楼层点赞
     *
     * @param fid
     * @param user
     * @return
     */
    @Override
    public boolean likeInc(Integer fid, User user) {
        if (floorMapper.likeInc(fid) == 1) {
            //通知
            //如果是自己点赞，不通知
            Floor f = getUidAndUsernameByFid(fid);
            if (!Objects.equals(f.getUid(), user.getUid())) {
                //通过楼层uid获取楼层stuid
                User u = userService.getStuIdById(f.getUid());
                NoticeMessage noticeMessage = new NoticeMessage();
                noticeMessage.setContent(u.getUsername() + "给你点赞了");
                noticeMessage.setUid(user.getUid());
                noticeMessage.setFid(fid);
                noticeMessage.setType(1);
                noticeMessage.setUsername(user.getUsername());
                messageQueueUtils.sendMessage(u.getStudentId(), noticeMessage);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean delFloor(Integer fid, User user) {
        Integer uid = user.getUid();
        Floor floor = getUidAndUsernameByFid(fid);
        if (!floor.getUid().equals(uid)) return false;
        return floorMapper.deleteById(fid) == 1;
    }

    @Override
    public Floor getUidAndUsernameByFid(Integer fid) {
        QueryWrapper<Floor> qw = new QueryWrapper<>();
        qw.select("username", "uid");
        qw.eq("fid", fid);
        return floorMapper.selectOne(qw);
    }

    @Override
    public List<Integer> getMyFloors(Integer uid) {
        QueryWrapper<Floor> qw = new QueryWrapper<>();
        qw.eq("uid",uid);

        return floorMapper.selectList(qw).stream().map(Floor::getFid).collect(Collectors.toList());
    }
}
